import LoadManager from "./LoadManager";

export default class UIManager {
    constructor()
    {

    }
    private static _instance:UIManager;
    
    public static get instance() : UIManager {
        if(!this._instance)
        {
            this._instance = new UIManager()
        }
        return this._instance
    }
    private getUIConstIdByNode(targetNode:cc.Node):string {
        for (const UIConstId in this.viewList) {
            if (this.viewList.hasOwnProperty(UIConstId)) {
                const viewNode = this.viewList[UIConstId];
                if (viewNode==targetNode)
                {
                    return UIConstId
                }
            }
        }
        return ""
    }
    private viewList:Array<cc.Node> = []
    private onClose(event:cc.Event.EventTouch) {
        let btn_close:cc.Node = event.currentTarget;
        let viewNode:cc.Node = btn_close.parent
        let UIConstId:string = this.getUIConstIdByNode(viewNode)
        this.hide(UIConstId,true)
    }
    /**
     * show
     */
    public show(UIConstId:string,isEffect:boolean) {
        const prefab:cc.Prefab = LoadManager.instance.getPrefabResByUrl(UIConstId)
        if (!prefab)
        {
            console.log("弹窗失败");
            return
        }
        let viewNode:cc.Node
        if (this.viewList[UIConstId])
        {
            viewNode = this.viewList[UIConstId]
        }
        else
        {
            viewNode = cc.instantiate(prefab)
            this.viewList[UIConstId] = viewNode
        }
        let btn_close:cc.Node = viewNode.getChildByName("btn_close")
        if (btn_close)
        {
            btn_close.on(cc.Node.EventType.TOUCH_END,this.onClose,this)
        }
        let scene:cc.Scene = cc.director.getScene()
        scene.addChild(viewNode)
        viewNode.x = cc.winSize.width/2
        viewNode.y = cc.winSize.height/2
        if (isEffect)
        {
            viewNode.setScale(0.1,0.1)
            let action:cc.ActionInterval = cc.scaleTo(0.3,1,1)
            viewNode.runAction(action)
        } 
    }
    private destroy(viewNode:cc.Node) {
        let UIConstId:string = this.getUIConstIdByNode(viewNode)
        viewNode.destroy()
        this.viewList[UIConstId] = null;
    }
    /**
     * hide
     */
    public hide(UIConstId:string,isEffect:boolean) {
        let viewNode:cc.Node = this.viewList[UIConstId]
        if (!viewNode)
        {
            return
        }

        if (isEffect)
        {
            let callFunc:cc.ActionInstant = cc.callFunc(this.destroy,this)
            let action:cc.ActionInterval = cc.sequence(cc.scaleTo(0.3,0.1,0.1),callFunc)
            viewNode.runAction(action)
        }
        else
        {
            this.destroy(viewNode)
        }
    }
}
